package org.darcy.controller.portal;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.darcy.entity.BizAd;
import org.darcy.entity.BizComment;
import org.darcy.entity.SysLink;
import org.darcy.framework.annotation.BussinessLog;
import org.darcy.framework.blog.business.enums.CommentStatusEnum;
import org.darcy.framework.blog.business.enums.FileUploadType;
import org.darcy.framework.blog.core.websocket.WebSocketUtil;
import org.darcy.framework.blog.core.websocket.WebsocketServer;
import org.darcy.framework.blog.exception.BlogArticleException;
import org.darcy.framework.blog.exception.BlogCommentException;
import org.darcy.framework.blog.exception.BlogLinkException;
import org.darcy.framework.blog.file.FileUploader;
import org.darcy.framework.blog.file.entity.VirtualFile;
import org.darcy.framework.blog.plugin.file.GlobalFileUploader;
import org.darcy.framework.model.ResponseVO;
import org.darcy.framework.util.RestClientUtil;
import org.darcy.framework.util.ResultUtil;
import org.darcy.model.BizArticleModel;
import org.darcy.model.BizCommentModel;
import org.darcy.service.BizAdService;
import org.darcy.service.BizArticleService;
import org.darcy.service.BizCommentService;
import org.darcy.service.SysLinkService;
import org.darcy.service.SysNoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * 网站接口类，申请友链、评论、点赞等
 *
 */
@Slf4j
@RestController
@RequestMapping("/api")
public class ApiController {

	@Autowired
	private SysLinkService sysLinkService;
	@Autowired
	private BizCommentService commentService;
	@Autowired
	private BizArticleService articleService;
	@Autowired
	private SysNoticeService noticeService;
	@Autowired
	private BizAdService adService;

	@PostMapping("/autoLink")
	@BussinessLog(value = "自助申请友链")
	public ResponseVO autoLink(@Validated SysLink link, BindingResult bindingResult) {
		log.info("申请友情链接......");
		log.info(JSON.toJSONString(link));
		if (bindingResult.hasErrors()) {
			return ResultUtil.error(bindingResult.getFieldError().getDefaultMessage());
		}
		try {
			sysLinkService.autoLink(link);
		} catch (BlogLinkException e) {
			log.error("客户端自助申请友链发生异常", e);
			return ResultUtil.error(e.getMessage());
		}
		return ResultUtil.success("已成功添加友链，祝您生活愉快！");
	}

	@PostMapping("/qq/{qq}")
	@BussinessLog(value = "获取QQ信息")
	public ResponseVO qq(@PathVariable("qq") String qq) {
		if (StringUtils.isEmpty(qq)) {
			return ResultUtil.error("");
		}
		Map<String, String> resultMap = new HashMap<>(4);
		String nickname = "匿名";
		String json = RestClientUtil.get("https://r.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?uins=" + qq, "GBK");
		if (!StringUtils.isEmpty(json)) {
			try {
				json = json.replaceAll("portraitCallBack|\\\\s*|\\t|\\r|\\n", "");
				json = json.substring(1, json.length() - 1);
				log.info(json);
				JSONObject object = JSONObject.parseObject(json);
				JSONArray array = object.getJSONArray(qq);
				nickname = array.getString(6);
			} catch (Exception e) {
				log.error("通过QQ号获取用户昵称发生异常", e);
			}
		}
		resultMap.put("avatar", "https://q1.qlogo.cn/g?b=qq&nk=" + qq + "&s=40");
		resultMap.put("nickname", nickname);
		resultMap.put("email", qq + "@qq.com");
		resultMap.put("url", "https://user.qzone.qq.com/" + qq);
		return ResultUtil.success(null, resultMap);
	}

	@PostMapping("/comments")
	@BussinessLog(value = "评论列表", save = false)
	public ResponseVO comments(BizCommentModel vo) {
		vo.setStatus(CommentStatusEnum.APPROVED.toString());
		return ResultUtil.success(null, commentService.list(vo));
	}

	@PostMapping("/comment")
	@BussinessLog(value = "发表评论")
	public ResponseVO comment(BizComment comment) {
		try {
			commentService.comment(comment);
		} catch (BlogCommentException e) {
			return ResultUtil.error(e.getMessage());
		}
		return ResultUtil.success("评论发表成功，系统正在审核，请稍后刷新页面查看！");
	}

	@PostMapping("/doSupport/{id}")
	@BussinessLog(value = "点赞评论{1}")
	public ResponseVO doSupport(@PathVariable("id") Long id) {
		try {
			commentService.doSupport(id);
		} catch (BlogCommentException e) {
			return ResultUtil.error(e.getMessage());
		}
		return ResultUtil.success("");
	}

	@PostMapping("/doOppose/{id}")
	@BussinessLog(value = "点踩评论{1}")
	public ResponseVO doOppose(@PathVariable("id") Long id) {
		try {
			commentService.doOppose(id);
		} catch (BlogCommentException e) {
			return ResultUtil.error(e.getMessage());
		}
		return ResultUtil.success("");
	}

	@PostMapping("/doPraise/{id}")
	@BussinessLog(value = "点赞文章{1}")
	public ResponseVO doPraise(@PathVariable("id") Long id) {
		try {
			articleService.doPraise(id);
		} catch (BlogArticleException e) {
			return ResultUtil.error(e.getMessage());
		}
		return ResultUtil.success("");
	}

	@PostMapping("/listNotice")
	@BussinessLog(value = "公告列表", save = false)
	public ResponseVO listNotice() {
		return ResultUtil.success("", noticeService.listRelease());
	}

	@PostMapping("/verifyArticlePassword")
	@BussinessLog(value = "验证文章密码", save = false)
	public ResponseVO verifyArticlePassword(Long articleId, String password) {
		if (StringUtils.isEmpty(password)) {
			return ResultUtil.error("文章密码错误");
		}
		BizArticleModel article = articleService.getDetail(articleId);
		if (null == article) {
			return ResultUtil.error(String.format("文章【%s】不存在！", articleId));
		}
		if (article.getPassword().equals(password)) {
			return ResultUtil.success("文章密码验证通过", article.getContent());
		}
		return ResultUtil.error("文章密码错误");
	}

	@GetMapping("/ads")
	public ResponseVO ads() {
		List<BizAd> list = adService.getList(null);
		Map<String, BizAd> res = null;
		if (!CollectionUtils.isEmpty(list)) {
			res = list.stream()
					.collect(Collectors.toMap(BizAd::getPosition, Function.identity(), (key1, key2) -> key2));
		}
		return ResultUtil.success(res);
	}

	@Autowired
	private WebsocketServer websocketServer;

	@BussinessLog("wangEditor编辑器中上传文件")
	@RequiresPermissions("article:publish")
	@PostMapping("/uploadFile")
	public ResponseVO uploadFile(@RequestParam("file") MultipartFile file) {
		FileUploader uploader = new GlobalFileUploader();
		VirtualFile virtualFile = uploader.upload(file, FileUploadType.SIMPLE.getPath(), true);
		return ResultUtil.success("图片上传成功", virtualFile.getFullFilePath());
	}

	@BussinessLog("simpleMD编辑器中上传文件")
	@RequiresPermissions("article:publish")
	@PostMapping("/uploadFileForMd")
	public Object uploadFileForMd(@RequestParam("file") MultipartFile file) {
		FileUploader uploader = new GlobalFileUploader();
		VirtualFile virtualFile = uploader.upload(file, FileUploadType.SIMPLE.getPath(), true);
		Map<String, Object> resultMap = new HashMap<>(3);
		resultMap.put("success", 1);
		resultMap.put("message", "上传成功");
		resultMap.put("filename", virtualFile.getFullFilePath());
		return resultMap;
	}

	/**
	 * 发送消息通知
	 *
	 * @return
	 */
	@RequiresPermissions("notice")
	@PostMapping("/notice")
	@BussinessLog("通过websocket向前台发送通知")
	public ResponseVO<String> notice(String msg) throws UnsupportedEncodingException {
		WebSocketUtil.sendNotificationMsg(msg, websocketServer.getOnlineUsers());
		return ResultUtil.success("消息发送成功");
	}

}
